<script setup lang="ts">
defineOptions({
  name: "alarmTable"
});

import { ref, reactive, toRefs, onMounted, nextTick, onUnmounted, watch, getCurrentInstance } from "vue";
import { queryDictData } from "@/api/common";
import { PxMessage } from "px-ui";
import {
  queryWeatherData,
  getFabZone,
  getReadersInZone,
  getPointNewValue,
  getPointsCurve,
  addRemake,
  remakeHistory,
  queryChildByTypeCodeAndItemValue,
  queryAreaWornings
} from "@/api/machineClass";
import { useRouter } from "vue-router";
import { error } from "console";

const router = useRouter();

interface Props {
  /**  有 tab 时传入 */
  activeName?: string;
  /**当前选中的区域 */
  activeIndex?: number;
  /**  当前区域 */
  area?: string;
}

const props = withDefaults(defineProps<Props>(), {});

const { proxy }: any = getCurrentInstance();

const state = reactive<any>({
  queryParams: {
    pageNum: 1,
    pageSize: 10
    // lifecycle: 4
  },
  queryParams2: {
    pageNum: 1,
    pageSize: 10
  },
  queryHistoryParams: {},
  dateRange: [],
  tableData: [],
  contentList: [],
  areaData: []
});

const { queryParams, queryHistoryParams, dateRange, areaData, tableData, queryParams2, contentList } = toRefs(state);

const defaultTime: [Date, Date] = [new Date(2000, 1, 1, 0, 0, 0), new Date(2000, 1, 1, 23, 59, 59)];

const loading = ref(false);
const filterList = ref([]);
const typeList = ref([
  {
    value: "hour",
    label: "小时"
  }
]);
const testCompanyList = ref([
  {
    value: 4,
    label: "近4小时"
  },
  {
    value: 8,
    label: "近8小时"
  },
  {
    value: 16,
    label: "近16小时"
  }
]);

const minitesList = ref([
  {
    value: 10,
    label: "10分钟"
  },
  {
    value: 20,
    label: "20分钟"
  },
  {
    value: 30,
    label: "30分钟"
  }
]);

const total = ref(0);
const total2 = ref(0);
const searchId = ref("");
const contentVisible = ref(false);
const contentTextVisible = ref(false);
const chosedAlarm = ref("");
const viewAlarm = ref("");
const alarmRemake = ref("");
const hishoryLoading = ref(false);

// 日期转化
const initDate = (val: number) => {
  const now = new Date();
  const utcTime = now.toISOString();
  const beijingTime = new Date(utcTime).getTime() + 8 * 60 * 60 * 1000;
  const start = beijingTime - val * 60 * 60 * 1000;
  const startTime = new Date(start).toISOString().slice(0, 19).replace("T", " ");
  const endTime = new Date(beijingTime).toISOString().slice(0, 19).replace("T", " ");
  return [startTime, endTime];
};

const handleAreaChange = (val: any) => {
  // queryParams.value[`${val.indexOf("ROOM") === -1 ? "areaId" : "roomId"}`] = val;
};

const handleChange = (val: number) => {
  if (val) {
    dateRange.value = initDate(val);
  }
};

// 查询报警明细
const queryTable = async () => {
  loading.value = true;
  const params = { ...queryParams.value };
  params[`${searchId.value.indexOf("ROOM") === -1 ? "areaId" : "roomId"}`] =
    searchId.value.indexOf("ROOM") === -1 ? [searchId.value] : searchId.value;
  const param = proxy.addDateRange(params, dateRange.value, "startTime", "endTime");
  const res: any = await queryAreaWornings(param).catch(error => {
    loading.value = false;
  });
  tableData.value = res?.data || [];
  total.value = res?.total || 0;
  loading.value = false;
};

// 重置筛选条件
const resetTable = async () => {
  dateRange.value = [];
  queryParams.value = {
    pageNum: 1,
    pageSize: 10
  };
  searchId.value = areaData.value[props.activeIndex].code; // 重置为当前选中的区域
  queryTable();
};

const addAlarmRemake = (row: any) => {
  chosedAlarm.value = "alarm_" + row.alarmId;
  alarmRemake.value = "";
  contentTextVisible.value = true;
};

const addcontent = () => {
  addRemake({
    businessKey: chosedAlarm.value,
    content: alarmRemake.value
  }).then(res => {
    PxMessage({
      message: "批注成功",
      type: "success"
    });
    contentTextVisible.value = false;
  });
};

const getcontentList = row => {
  viewAlarm.value = row ? "alarm_" + row.alarmId : "";
  contentVisible.value = true;
  queryAlarmHistory();
};

const queryAlarmHistory = async () => {
  hishoryLoading.value = true;
  const res: any = await remakeHistory({
    businessKey: viewAlarm.value,
    ...queryHistoryParams.value
  });
  contentList.value = res?.data || [];
  total2.value = res?.total || 0;
  hishoryLoading.value = false;
};

const handleBtnClick = row => {
  router.push({
    path: "/machine/operation/environmentTestManage/components/alarmDetail",
    query: {
      area: searchId.value
    }
  });
};

// 获取区域列表
const queryAreaList = async (id: string) => {
  const data: any = await getFabZone();
  areaData.value = data;
  searchId.value = areaData.value[props.activeIndex].code; // 默认查询选中的区域
  queryTable();
};

const queryAlarmList = async () => {
  // 通过厂区字典查询区域
  const codes: any = await queryChildByTypeCodeAndItemValue({
    value: "CR_ALL_CODES",
    typeCode: "MCTS"
  });
  const id = JSON.parse(codes.filter(item => item.itemValue === "CR_POSITION_CODE")[0].itemDesc)[0].facCode; // 暂时写死一期厂区
  await queryAreaList(id);
};

watch(
  () => props.activeIndex,
  newVal => {
    console.log(newVal, "newValnewValnewVal");
    queryAlarmList();
  }
);

onMounted(async () => {
  filterList.value = await queryDictData({ typeCode: "ALARM_LEVEL" });
  await queryAlarmList();
});
</script>

<template>
  <div>
    <px-form ref="queryRef" class="custom-form-ui-new" :model="queryParams" :inline="true" label-width="68px">
      <px-form-item label="名称" prop="point" style="width: 220px">
        <!-- <px-select v-model="queryParams.point" clearable filterable placeholder="请选择名称">
          <px-option v-for="item in areaList" :key="item.value" :label="item.label" :value="item.value" />
        </px-select> -->
        <px-input v-model="queryParams.point" clearable placeholder="请输入名称" />
      </px-form-item>
      <px-form-item label="级别" prop="alarmLevel" style="width: 220px">
        <px-select v-model="queryParams.alarmLevel" clearable filterable placeholder="请选择级别">
          <px-option v-for="item in filterList" :key="item.id" :label="item.name" :value="item.value" />
        </px-select>
      </px-form-item>
      <px-form-item label="区域" prop="areaId" style="width: 220px">
        <px-select v-model="searchId" placeholder="请选择区域" filterable @change="handleAreaChange">
          <px-option v-for="item in areaData" :key="item.value" :label="item.name" :value="item.code" />
        </px-select>
      </px-form-item>
      <!-- <px-form-item label="房间" prop="areaId" style="width: 220px">
      <px-select v-model="queryParams.roomId" clearable filterable placeholder="请选择房间">
        <px-option v-for="item in areaData" :key="item.value" :label="item.name" :value="item.code" />
      </px-select>
    </px-form-item> -->
      <px-form-item label="时间日期" style="width: 460px">
        <px-date-picker
          v-model="dateRange"
          :clearable="false"
          type="datetimerange"
          start-placeholder="开始日期"
          end-placeholder="结束日期"
          :defaultTime="defaultTime"
          format="YYYY-MM-DD HH:mm:ss"
          value-format="YYYY-MM-DD HH:mm:ss"
        />
      </px-form-item>
      <px-form-item label="周期" prop="lifecycle" style="width: 220px">
        <px-select v-model="queryParams.lifecycle" clearable filterable placeholder="请选择周期" @change="handleChange">
          <px-option v-for="item in testCompanyList" :key="item.value" :label="item.label" :value="item.value" />
        </px-select>
      </px-form-item>
      <px-form-item>
        <px-button type="primary" @click="queryTable">查询</px-button>
        <px-button @click="resetTable">重置</px-button>
      </px-form-item>
    </px-form>
    <px-table v-loading="loading" :header-cell-style="{ background: '#e7eefb', color: '#000' }" border :data="tableData" show-overflow-tooltip>
      <px-table-column label="序号" width="60" align="center" fixed="left">
        <template #default="{ $index }">
          {{ (queryParams.pageNum - 1) * queryParams.pageSize + $index + 1 }}
        </template>
      </px-table-column>
      <!-- <px-table-column width="100" label="厂区" align="center" prop="id" /> -->
      <px-table-column label="时间" align="center" prop="alarmTime" width="160" />
      <!-- <px-table-column label="组" align="center" prop="factoryId" /> -->
      <px-table-column label="名称" align="center" prop="point" />
      <px-table-column label="报警信息" align="center" prop="alarmContent" width="100" />
      <px-table-column label="级别" align="center" prop="alarmLevel" />
      <px-table-column label="当前值" align="center" prop="realityValue" />
      <!-- <px-table-column label="报警限" align="center" prop="settingValue" /> -->
      <px-table-column label="状态" align="center" prop="alarmStatus" />
      <!-- <px-table-column label="报警持续时间" align="center" prop="alarmDurationTime" width="180" /> -->
      <!-- <px-table-column label="未确认持续时间" align="center" prop="updateTime" width="160" /> -->
      <!-- <px-table-column label="曲线" align="center" prop="">
        <template #default="scope">
          <px-tooltip content="曲线" placement="top">
            <px-button v-has="'FFU_LEDGER_EDIT'" link type="primary" icon="Chart" @click="handleBtnClick(scope.row)" />
          </px-tooltip>
        </template>
      </px-table-column>
      <px-table-column label="操作" align="center" width="120" class-name="small-padding fixed-width">
        <template #default="scope">
          <px-tooltip content="批注" placement="top">
            <px-button v-has="'FFU_LEDGER_EDIT'" link type="primary" icon="Edit" @click="addAlarmRemake(scope.row)" />
          </px-tooltip>
          <px-tooltip content="历史批注" placement="top">
            <px-button v-has="'FFU_LEDGER_COPY'" link type="primary" icon="Clock" @click="getcontentList(scope.row)" />
          </px-tooltip>
        </template>
      </px-table-column> -->
      <template #empty>
        <px-empty :image-size="150" />
      </template>
    </px-table>

    <pagination v-show="total > 0" v-model:page="queryParams.pageNum" v-model:limit="queryParams.pageSize" :total="total" @pagination="queryTable" />
    <px-dialog v-model="contentVisible" title="批注历史" width="956" align-center>
      <px-table v-loading="hishoryLoading" class="digtable1" :data="contentList" height="250" show-overflow-tooltip border>
        <px-table-column label="时间" prop="createTime">
          <template #default="scope">
            <span>{{ scope.row.createTime }}</span>
          </template>
        </px-table-column>
        <px-table-column label="批注人" prop="creator">
          <template #default="scope">
            <span>{{ scope.row.creator }}</span>
          </template>
        </px-table-column>
        <px-table-column label="内容" prop="content">
          <template #default="scope">
            <span>{{ scope.row.content }}</span>
          </template>
        </px-table-column>

        <template #empty>
          <px-empty :image-size="150" />
        </template>
      </px-table>
      <pagination
        v-show="total2 > 0"
        v-model:page="queryParams2.pageNum"
        v-model:limit="queryParams2.pageSize"
        style="margin-bottom: -10px"
        :total="total2"
        @pagination="queryAlarmHistory"
      />
      <!-- <template #footer>
        <span class="dialog-footer">
          <px-button @click="progressVisible = false">取消</px-button>
          <px-button type="primary" @click="addRukudetails()"> 确认 </px-button>
        </span>
      </template> -->
    </px-dialog>
    <px-dialog v-model="contentTextVisible" title="批注" width="677" align-center>
      <px-row class="contentrow">
        <px-col :span="24">
          <px-input v-model="alarmRemake" style="margin-top: 16px" :rows="2" type="textarea" placeholder="请输入" />
        </px-col>
      </px-row>
      <template #footer>
        <span class="dialog-footer">
          <px-button @click="contentTextVisible = false">取消</px-button>
          <px-button type="primary" @click="addcontent()"> 保存 </px-button>
        </span>
      </template>
    </px-dialog>
  </div>
</template>
